package models;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import helpers.GeneralHelper;

import javax.cache.Cache;

import com.googlecode.objectify.Key;
import com.googlecode.objectify.Objectify;
import com.googlecode.objectify.ObjectifyService;

import entities.Website;

public class WebsiteModel {
	private Objectify ofy;
	
	private Cache cache = null;
	
	private String prefix = "website_";
	
	private static WebsiteModel instance = null;
	
	public static WebsiteModel getInstance() {
		if (instance == null) {
			instance = new WebsiteModel();
		}
		
		return instance;
	}
	
	private WebsiteModel() {
		try {
			ObjectifyService.register(Website.class);
		} catch (Exception e) {
			// TODO: handle exception
		}
		
		cache = GeneralHelper.getCache();
		ofy = GeneralHelper.getObjectify();
	}
	
	public Website get(String id) {
		Website website = new Website();
		
		try {
			website = ofy.get(new Key<Website>(Website.class, id));
		} catch (Exception e) {
			website = null;
		}
		
		return website;
	}
	
	public List<Website> list(int page, int limit) {
		List<Website> websites = new ArrayList<Website>();
		
		int start = (page - 1) * limit;
		websites = ofy.query(Website.class).limit(limit).offset(start).list();
		
		return websites;
	}
	
	public void insert(Website website) {
		ofy.put(website);
	}
	
	public void delete(Website website) {
		ofy.delete(website);
	}
	
	public Map<String, Website> getByListId(List<String> ids) {
		Map<String, Website> websites = new TreeMap<String, Website>();
		
		websites = ofy.get(Website.class, ids);
		
		return websites;
	}
}
